package com.lottery.game.core.modules.service.app;

import com.alibaba.fastjson.JSONObject;
import com.lottery.game.common.constants.GameConstants;
import com.lottery.game.common.utils.DateUtils;
import com.lottery.game.common.utils.UUIDUtils;
import com.lottery.game.core.configuration.SftpUtils;
import com.lottery.game.core.modules.entity.user.GameUser;
import com.lottery.game.core.modules.mapper.GameUserDao;
import com.lottery.game.core.modules.mapper.OperationalSetDao;
import com.lottery.game.core.modules.service.redis.RedisService;
import com.lottery.game.core.utils.ResultCode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class OperationalSetService {

    @Autowired
    private OperationalSetDao operationalSetDao;

    @Autowired
    private GameUserDao gameUserDao;

    @Autowired
    private RedisService redisService;


    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private WebsocketMessageService websocketMessageService;

    @Autowired
    private SftpUtils sftpUtils;

    @Transactional(readOnly = true)
    public Map<String, String> queryOperationalSetInfo() throws Exception {
        Map<String, String> map = this.operationalSetDao.queryOperationalSetInfo();
        if (map != null) {
            String websiteTitle = map.get("website_title");
            String roomKeyWordsShielding = map.get("room_key_words_shielding");
            String appDownLoadLink = map.get("app_download_link");
            String advertisementPrompt = map.get("advertisement_prompt");
            String roomAdvertisement = map.get("room_advertisement");
            String smsInterfaceKey = map.get("sms_interface_key");
            String qqOnlineCustomerService = map.get("qq_Online_Customer_Service");
            String websitePhoto = map.get("website_photo");
            Map<String, String> reulstMap = new HashMap<>();
            reulstMap.put("websiteTitle", websiteTitle);
            reulstMap.put("roomKeyWordsShielding", roomKeyWordsShielding);
            reulstMap.put("appDownLoadLink", appDownLoadLink);
            reulstMap.put("advertisementPrompt", advertisementPrompt);
            reulstMap.put("roomAdvertisement", roomAdvertisement);
            reulstMap.put("smsInterfaceKey", smsInterfaceKey);
            reulstMap.put("qqOnlineCustomerService", qqOnlineCustomerService);
            reulstMap.put("websitePhoto", websitePhoto);
            return reulstMap;
        }
        return null;
    }

    /**
     * Description: 向前端发送消息
     *
     * @author zhuiyv
     * @date 2018-07-24
     */
    private void sendMsgToClient(String chatType, String status, String phone) {
        GameUser user = this.gameUserDao.getGameUserByUserName(phone);
        if (user != null) {
            Map<String, Object> msgMap = new HashMap<>();
            msgMap.put("type", chatType);
            msgMap.put("status", status);

            String sendMsg = JSONObject.toJSONString(msgMap);

            String senderNickname = GameConstants.SENDER_SYSTEM;
            String userId = user.getId();
            String roomNumber = "";

			websocketMessageService.saveWebsocketMessage(senderNickname, sendMsg, userId, roomNumber, chatType, null , 0);
//            webSocketService.sendToTheUser(sendMsg, user.getId(), GameConstants.SYS_PARAM_CHATID);
        }
    }


    public Map<String, Object> updateUserStatus(String phone, String bannedStatus, String reason) {
        Map<String, Object> reulstMap = new HashMap<>();
        try {
            Map<String, String> map = new HashMap<>();
            if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(bannedStatus)) {
                reulstMap.put("msg", "禁言失败,参数错误!");
                reulstMap.put("status", "fail");
                return reulstMap;
            }
            GameUser gameUser = this.gameUserDao.getUserByPhone(phone);
            //禁言的时候操作
            if (bannedStatus.equals("1") && gameUser != null) {

                if (gameUser.getStatus() != null && gameUser.getStatus().equals("1")) {
                    reulstMap.put("msg", "该用户已被禁言");
                    reulstMap.put("status", "fail");
                    return reulstMap;
                }
            }
            map.put("phone", phone);
            map.put("bannedStatus", bannedStatus);
            map.put("reason", reason);
            int num = this.gameUserDao.updateUserStatus(map);
            if (num > 0) {
                //发送消息
                sendMsgToClient(GameConstants.SYS_MSG_BANNED, bannedStatus, phone);
                reulstMap.put("msg", "禁言成功!");
                reulstMap.put("status", "success");
            } else {
                reulstMap.put("msg", "账号不存在!");
                reulstMap.put("status", "fail");
            }
            return reulstMap;
        } catch (Exception e) {
            e.printStackTrace();
            reulstMap.put("errMsg", e.toString());
            reulstMap.put("msg", "禁言失败!");
            reulstMap.put("status", "fail");
            return reulstMap;
        }
    }

    public Map<String, Object> udpatefenghaostatus(String phone, String fenghaoStatus, String reason) {
        Map<String, Object> reulstMap = new HashMap<>();
        try {
            Map<String, String> map = new HashMap<>();
            if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(fenghaoStatus)) {
                reulstMap.put("message", "封号失败,参数错误!");
                reulstMap.put("status", "fail");
                return reulstMap;
            }
            GameUser gameUser = this.gameUserDao.getUserByPhone(phone); //根据手机号去查询用户信息
            if (fenghaoStatus.equals("1") && gameUser != null) {
                if (gameUser.getFenghaostatus() != null && gameUser.getFenghaostatus().equals("1")) {
                    reulstMap.put("message", "该用户已被封号!");
                    reulstMap.put("status", "fail");
                    return reulstMap;
                }
            }

            map.put("phone", phone);
            map.put("fenghaoStatus", fenghaoStatus);
            map.put("reason", reason);
            int num = this.gameUserDao.udpatefenghaostatus(map);

            if (gameUser != null) {
                if (num > 0) {
                    //发送消息
                    sendMsgToClient(GameConstants.SYS_MSG_CLOSEUSER, fenghaoStatus, phone);
                    this.redisService.delete("UUID" + gameUser.getId()); //提出用户
                    reulstMap.put("message", "封号成功!");
                    reulstMap.put("status", "success");
                }
            } else {
                reulstMap.put("message", "账号不存在!");
                reulstMap.put("status", "fail");
            }
            return reulstMap;
        } catch (Exception e) {
            e.printStackTrace();
            reulstMap.put("errMsg", e.toString());
            reulstMap.put("message", "封号失败!");
            reulstMap.put("status", "fail");
            return reulstMap;
        }
    }

    public Map<String, Object> addIPBlacklist(String phone, String reason) {//添加IP的黑名单
        Map<String, Object> reulstMap = new HashMap<>();
        try {
            if (StringUtils.isEmpty(phone)) {
                reulstMap.put("message", "封号IP失败,参数不能为空!");
                reulstMap.put("status", "fail");
                return reulstMap;
            }
            GameUser gameUser = this.gameUserDao.getUserByPhone(phone);
            String loginIpArea = "";
            if (gameUser.getLogin_ip_area() != null && !"".equals(gameUser.getLogin_ip_area())) {
                loginIpArea = gameUser.getLogin_ip_area();
            } else {
                reulstMap.put("message", "IP不存在,用户没有登录过系统!");
                reulstMap.put("status", "fail");
                return reulstMap;
            }
            String ip = loginIpArea.substring(0, loginIpArea.indexOf("|"));
            String uuid = UUIDUtils.randomUUID();

            Map<String, Object> ipblackMap = this.operationalSetDao.queryIPBlacklist(ip);
            if (ipblackMap != null) {
                reulstMap.put("message", "要封的IP已存在！");
                reulstMap.put("status", "fail");
                return reulstMap;
            }


            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("uuId", uuid);
            itemMap.put("IP", ip);
            itemMap.put("phone", phone);
            itemMap.put("createTime", DateUtils.getNowDateString());
            itemMap.put("reason", reason);

            int num = this.operationalSetDao.addIPBlacklist(itemMap);
            if (num > 0) {
                //发送消息
                sendMsgToClient(GameConstants.SYS_MSG_CLOSEIP, "1", phone);
                this.redisService.delete("UUID" + gameUser.getId()); //提出用户
                reulstMap.put("message", "封IP成功!");
                reulstMap.put("status", "success");
            } else {
                reulstMap.put("message", "账号不存在!");
                reulstMap.put("status", "faill");
            }
            return reulstMap;
        } catch (Exception e) {
            e.printStackTrace();
            reulstMap.put("errMsg", e.toString());
            reulstMap.put("message", "封IP失败!");
            reulstMap.put("status", "faill");
            return reulstMap;
        }

    }

    @Transactional(readOnly = false)
    public Map<String, Object> deleteIPBlacklist(String ip) {
        Map<String, Object> reulstMap = new HashMap<>();
        try {
            if (StringUtils.isEmpty(ip)) {
                reulstMap.put("message", "参数不能为空!");
                reulstMap.put("status", "faill");
                return reulstMap;
            }
		 /* GameUser gameUser=gameUserDao.getUserByPhone(phone);
		  String loginIpArea=gameUser.getLogin_ip_area();
		  String ip=loginIpArea.substring(0,loginIpArea.indexOf("|"));*/

            int num = this.operationalSetDao.deleteIPBlacklist(ip);
            if (num > 0) {
                reulstMap.put("message", "解封IP成功!");
                reulstMap.put("status", "success");
            } else {
                reulstMap.put("message", "账号不存在!");
                reulstMap.put("status", "faill");
            }
            return reulstMap;
        } catch (Exception e) {
            e.printStackTrace();
            reulstMap.put("errMsg", e.toString());
            reulstMap.put("message", "解封IP失败!");
            reulstMap.put("status", "faill");
            return reulstMap;
        }

    }


    /**
     * 添加轮播图
     *
     * @param map
     * @return
     */
    public int addCarousel(Map<String, String> map) {
        return 0;
    }


    /**
     * 删除轮播图
     *
     * @param
     * @return
     */
    public Map<String, Object> deleteCarousel(String uuId) {
        Map<String, Object> reulstMap = new HashMap<>();
        try {
            //根据UUID查询下数据的图片地址
            Map<String, Object> map = this.operationalSetDao.queryCarouselById(uuId);

            String address = (String) map.get("pictureAddress");
            File file = new File(sftpUtils.getDefaultRootPath() + address);
            //删除服务器上面的图片
            boolean flag = file.delete();
            if (flag) {
            	this.operationalSetDao.deleteCarousel(uuId);

                reulstMap.put("message", "删除成功!");
                reulstMap.put("status", "success");
            } else {
                reulstMap.put("message", "删除失败!");
                reulstMap.put("status", "fail");
            }
            return reulstMap;
        } catch (Exception e) {
            //reulstMap.put("errMsg", e.toString());
            reulstMap.put("message", "系统异常:" + e.toString());
            reulstMap.put("status", "fail");
        }

        return reulstMap;

    }

    public int addCarousel(String uuId, String pictureAddress) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("uuId", uuId);
        paramMap.put("pictureAddress", pictureAddress);
        return this.operationalSetDao.addCarousel(paramMap);
    }

    public Map<String, Object> queryCarouselById(String uuId) {
        return this.operationalSetDao.queryCarouselById(uuId);
    }


    public List<Map<String, Object>> queryVirtualNumberSet() {
        return this.operationalSetDao.queryVirtualNumberSet();
    }

    public List<Map<String, Object>> queryVirtualNumberSetByNum(String roomNum) {
        return this.operationalSetDao.queryVirtualNumberSetByNum(roomNum);
    }

    /**
     * 添加单个机器人
     *
     * @param map
     * @return
     */
    public int addRobot(Map<String, String> map) {

        return this.operationalSetDao.addRobot(map);

    }

    /**
     * 修改单个机器人
     *
     * @param map
     * @return
     */
    public int updateRobot(Map<String, String> map) {
        return this.operationalSetDao.updateRobot(map);
    }

    /**
     * 删除机器人
     *
     * @param uuId
     * @return
     */
    public int deleteRobot(String uuId) {
        return this.operationalSetDao.deleteRobot(uuId);
    }

    @Transactional(readOnly = true)
    public Map<String, Object> queryRobotById(String uuId) {
        return this.operationalSetDao.queryRobotById(uuId);
    }

    @Transactional(readOnly = true)
    public List<String> queryRoomId() {
        return this.operationalSetDao.queryRoomId();
    }

    @Transactional(readOnly = true)
    public String querySchemeId(String schemeId) {
        return this.operationalSetDao.querySchemeId(schemeId);
    }

    /**
     * 根据房间号查询机器人信息
     *
     * @param roomNumber
     * @return
     */
    @Transactional(readOnly = true)
    public List<Map<String, Object>> queryRobotInfo(String roomNumber) {
        return this.operationalSetDao.queryRobotInfo(roomNumber);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> queryRobotData(String roomNumber) {
        return this.operationalSetDao.queryRobotData(roomNumber);
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> queryGameAnnouncement() {
        return this.operationalSetDao.queryGameAnnouncement();
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> queryGameDiscount() {
        return this.operationalSetDao.queryGameDiscount();
    }

    @Transactional(readOnly = true)
    public Map<String, Object> queryPlInfo(String roomNumber) {
        return this.operationalSetDao.queryPlInfo(roomNumber);
    }

    @Transactional(readOnly = true)
    public Map<String, Object> queryDictRobot() {
        List<Map<String, Object>> list = this.operationalSetDao.queryDictRobot();
        Map<String, Object> resulstMap = new HashMap<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> itemMap = list.get(i);
                if (itemMap.get("label").equals("size")) {
                    resulstMap.put("size", itemMap.get("value"));
                } else if (itemMap.get("label").equals("min")) {
                    resulstMap.put("min", itemMap.get("value"));
                } else if (itemMap.get("label").equals("max")) {
                    resulstMap.put("max", itemMap.get("value"));
                } else if (itemMap.get("label").equals("betChance")) {
                    resulstMap.put("betChance", itemMap.get("value"));
                }
            }
            return resulstMap;
        }
        return null;
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> queryGameNotify(String userId, String id) {
        return this.operationalSetDao.queryGameNotify(userId, id);
    }

    @Transactional(readOnly = true)
    public void updateGameNotifyRecordStatus(String id) {
    	this.operationalSetDao.updateGameNotify(id);
    }

    @Transactional(readOnly = true)
    public String gameNotifyPublish(String id, Integer type) {
        List<Map<String, Object>> map = this.operationalSetDao.queryGameNotifyRecordList(id);
        String result = String.valueOf(map.size());
        for (Map<String, Object> notify : map) {
            String userId = (String) notify.get("userId");
            Map<String, Object> contentMap = new HashMap<>(3);
            contentMap.put("notice",notify);
            contentMap.put("noticeType",type);
            contentMap.put("type", GameConstants.SYS_MSG_NOTICE);

            String sendMsg = JSONObject.toJSONString(contentMap);

            String senderNickname = GameConstants.SENDER_SYSTEM;
			      websocketMessageService.saveWebsocketMessage(senderNickname, sendMsg, userId, "", GameConstants.SYS_MSG_NOTICE, null, 0);
            try {
                result = ResultCode.SUCCESS;
                log.info("websocket send to {} - [{}] successfully", userId, notify.get("title"));
            }catch (Exception e){
                log.info("websocket send to {} error", userId, e);
            }
        }
        return result;
    }

    @Transactional(readOnly = true)
    public String queryDrawTip(){
        return this.operationalSetDao.queryDrawTip();
    }

}
